# coding: utf-8
# Author: Legend奇
# @Time： 2020/7/20 上午10:19

import uvicorn
from fastapi import FastAPI
from fastapi.exceptions import HTTPException
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import register_tortoise

from apps.iacs.handlers.user import user_router
from base.server import websocket_router
from settings import ALLOWED_HOSTS, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_USER, MYSQL_PORT, MYSQL_NAME
from utils.exception_handle import exception_handler
from utils.middlewares.auth_middleware import RedisTokenAuthentication

app = FastAPI()
app.add_exception_handler(HTTPException, exception_handler)
app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_HOSTS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_middleware(AuthenticationMiddleware, backend=RedisTokenAuthentication())
models = [
    'apps.iacs.models',
    'apps.log.models',
    'apps.resource.models',
    'apps.statistic.models',
    'apps.alarm.models',
]

register_tortoise(app,
                  db_url=f'mysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_NAME}',
                  modules={'models': models}
                  )
app.include_router(user_router, prefix='/api')
app.include_router(websocket_router, prefix='/websocket')


if __name__ == '__main__':
    uvicorn.run('main:app', port=7788, debug=True, reload=True)
